import { GraphQLError } from "graphql"
import * as jwt from 'jsonwebtoken'

import { SECRET_KEY } from '../config'
interface AuthUser {
  id: string,
  username: string
  phone: string
  token: string
  type: string
  name: string
}
const checkAuth = (context: any)  => {
  const authHeaders = context.req.headers.authorization
  if (authHeaders) {
    const token = authHeaders.split('Bearer ')[1];
    if (token) {
      try {
        const user = jwt.verify(token, SECRET_KEY) as AuthUser;
        return user;
      } catch (error) {
        throw new GraphQLError('Invaild/Expired token', {
          extensions: {
            code: 'UNAUTHENTICATED',
          },
        });
      }
    }
    throw new GraphQLError('authorization token must be "Bearer token"', {
      extensions: {
        code: 'UNAUTHENTICATED',
      },
    });
  }
  throw new GraphQLError('authorization token must be provided', {
    extensions: {
      code: 'UNAUTHENTICATED',
    },
  });
}
export default checkAuth